// -*-mode:c++; coding:utf-8-*-

#include <limits>
#include <cassert>
#include <algorithm>
#include <sstream>

#include "tablet_name_parser.hpp"

namespace xbase
{
	const uint64_t tablet_name_parser::bad_tablet_id = std::numeric_limits<uint64_t>::max();
	const char tablet_name_parser::s_comma_char = ',';
	const std::string tablet_name_parser::s_root_meta_tablet_name(".METADATA_1ST_LEVEL");

	
	void tablet_name_parser::parse() {
		if(s_root_meta_tablet_name.compare(0, s_root_meta_tablet_name.size(),
						   m_string_begin, m_size) == 0)
		{
			m_tablet_id = root_meta_tablet_id;
			m_first_comma = m_last_comma = NULL;
			return;
		}

		const char * const first_comma = std::find(m_string_begin, m_string_end, s_comma_char);
		if(first_comma != m_string_end)
		{
			m_first_comma = first_comma;
		}
		const char * const last_comma = m_string_end - 17;
		assert(*last_comma == s_comma_char);
		assert(first_comma < last_comma);
		m_last_comma = last_comma;

		std::stringstream stream;
		stream << std::string(m_last_comma + 1,
				      m_string_end);
		stream >> m_tablet_id;
		assert((m_tablet_id != bad_tablet_id) && (m_tablet_id != root_meta_tablet_id));
	}

} // namespace xbase
